<?php
require_once 'includes/header.php';
require_once 'includes/functions.php';
require_once 'includes/DatabaseHelper.php';
require_once '../includes/CognitiveModuleManager.php';
require_once '../includes/MediaManager.php';

// 初始化管理器
$moduleManager = new CognitiveModuleManager();
$mediaManager = new MediaManager();

// 默认为新增模式
$isEdit = false;
$contentId = 0;
$moduleId = 0;

// 检查是否传入了模块ID
if (isset($_GET['module_id'])) {
    $moduleId = intval($_GET['module_id']);
    $module = $moduleManager->getModuleById($moduleId);
    
    if (!$module) {
        $_SESSION['error_message'] = '找不到指定的认知模块';
        header('Location: cognitive_modules.php');
        exit;
    }
    
    // 新增内容模式
    $content = [
        'module_id' => $moduleId,
        'content_title' => '',
        'content_key' => '',
        'description' => '',
        'content_order' => 0,
        'color_code' => '',
        'title_audio_id' => null,
        'is_active' => 1
    ];
} 
// 检查是否传入了内容ID
else if (isset($_GET['id'])) {
    $contentId = intval($_GET['id']);
    $content = $moduleManager->getContentById($contentId);
    
    if (!$content) {
        $_SESSION['error_message'] = '找不到指定的内容';
        header('Location: cognitive_modules.php');
        exit;
    }
    
    $isEdit = true;
    $moduleId = $content['module_id'];
    $module = $moduleManager->getModuleById($moduleId);
} 
else {
    $_SESSION['error_message'] = '缺少必要参数';
    header('Location: cognitive_modules.php');
    exit;
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 获取表单数据
    $contentData = [
        'module_id' => $moduleId,
        'content_title' => $_POST['content_title'],
        'content_key' => $_POST['content_key'],
        'description' => $_POST['description'],
        'content_order' => intval($_POST['content_order']),
        'color_code' => $_POST['color_code'],
        'is_active' => isset($_POST['is_active']) ? 1 : 0
    ];
    
    // 处理音频上传
    if (isset($_FILES['title_audio']) && $_FILES['title_audio']['error'] == 0) {
        $uploadDir = ROOT_PATH . '/sounds/' . $module['age_group'] . '/' . $module['module_key'];
        $audioFile = $_FILES['title_audio'];
        
        $result = $mediaManager->uploadMedia($audioFile, 'audio', $uploadDir);
        if ($result) {
            $contentData['title_audio_id'] = $result['media_id'];
        }
    } else if (isset($_POST['existing_audio_id']) && !empty($_POST['existing_audio_id'])) {
        $contentData['title_audio_id'] = intval($_POST['existing_audio_id']);
    }
    
    $success = false;
    $message = '';
    
    // 验证表单数据
    if (empty($contentData['content_title'])) {
        $message = '内容标题不能为空';
    } elseif (empty($contentData['content_key'])) {
        $message = '内容标识符不能为空';
    } else {
        // 验证标识符唯一性
        $db = Database::getInstance();
        $checkSql = "SELECT COUNT(*) FROM cognitive_contents WHERE content_key = ? AND module_id = ?";
        $params = [$contentData['content_key'], $moduleId];
        
        if ($isEdit) {
            $checkSql .= " AND content_id != ?";
            $params[] = $contentId;
        }
        
        $count = $db->fetchColumn($checkSql, $params);
        
        if ($count > 0) {
            $message = '该模块下已存在相同的内容标识符';
        } else {
            // 保存数据
            if ($isEdit) {
                $success = $moduleManager->updateContent($contentId, $contentData);
                $message = $success ? '内容更新成功' : '内容更新失败';
            } else {
                $newContentId = $moduleManager->addContent($contentData);
                $success = $newContentId > 0;
                $message = $success ? '内容添加成功' : '内容添加失败';
                
                if ($success) {
                    $contentId = $newContentId;
                }
            }
        }
    }
    
    if ($success) {
        $_SESSION['success_message'] = $message;
        
        // 根据保存后动作决定跳转
        $nextAction = $_POST['after_save'] ?? 'list';
        
        if ($nextAction == 'add_examples' && $contentId > 0) {
            header('Location: cognitive_examples.php?content_id=' . $contentId);
        } else if ($nextAction == 'add_new' && $moduleId > 0) {
            header('Location: cognitive_content_edit.php?module_id=' . $moduleId);
        } else {
            header('Location: cognitive_contents.php?module_id=' . $moduleId);
        }
        exit;
    } else {
        $_SESSION['error_message'] = $message;
        $content = $contentData; // 回显表单数据
    }
}

// 获取已有的音频文件
$titleAudio = null;
if (!empty($content['title_audio_id'])) {
    $titleAudio = $mediaManager->getMediaById($content['title_audio_id']);
}

// 页面标题
$pageTitle = $isEdit ? '编辑内容' : '添加内容';
?>

<h1 class="mb-4"><i class="bi bi-card-text"></i> <?php echo $pageTitle; ?></h1>

<!-- 面包屑导航 -->
<nav aria-label="breadcrumb" class="mb-4">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="cognitive_modules.php?age_group=<?php echo urlencode($module['age_group']); ?>"><?php echo $module['age_group']; ?>岁认知模块</a></li>
        <li class="breadcrumb-item"><a href="cognitive_contents.php?module_id=<?php echo $moduleId; ?>"><?php echo htmlspecialchars($module['module_name']); ?></a></li>
        <li class="breadcrumb-item active" aria-current="page"><?php echo $isEdit ? htmlspecialchars($content['content_title']) : '新增内容'; ?></li>
    </ol>
</nav>

<!-- 操作区域 -->
<div class="card mb-4">
    <div class="card-body">
        <div class="d-flex justify-content-between">
            <a href="cognitive_contents.php?module_id=<?php echo $moduleId; ?>" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i> 返回内容列表
            </a>
            <?php if ($isEdit): ?>
                <div>
                    <a href="cognitive_examples.php?content_id=<?php echo $contentId; ?>" class="btn btn-primary">
                        <i class="bi bi-images"></i> 管理内容示例
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- 消息提示 -->
<?php if (isset($_SESSION['success_message'])): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?php echo $_SESSION['success_message']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php unset($_SESSION['success_message']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['error_message'])): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?php echo $_SESSION['error_message']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php unset($_SESSION['error_message']); ?>
<?php endif; ?>

<!-- 编辑表单 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-pencil-square me-1"></i> <?php echo $pageTitle; ?>
    </div>
    <div class="card-body">
        <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) . ($isEdit ? '?id=' . $contentId : '?module_id=' . $moduleId); ?>" enctype="multipart/form-data">
            <input type="hidden" name="module_id" value="<?php echo $moduleId; ?>">
            
            <!-- 基本信息 -->
            <h5 class="mb-3">基本信息</h5>
            
            <div class="row mb-3">
                <div class="col-md-6">
                    <label for="content_title" class="form-label">内容标题 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="content_title" name="content_title" value="<?php echo htmlspecialchars($content['content_title']); ?>" required>
                    <div class="form-text">例如：红色、圆形、数字1</div>
                </div>
                
                <div class="col-md-6">
                    <label for="content_key" class="form-label">内容标识符 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="content_key" name="content_key" value="<?php echo htmlspecialchars($content['content_key']); ?>" required pattern="[a-zA-Z0-9_\-]+" <?php echo $isEdit ? 'readonly' : ''; ?>>
                    <div class="form-text">用于标识内容，只能包含字母、数字、下划线和短横线，例如：red、circle、number1</div>
                </div>
            </div>
            
            <div class="mb-3">
                <label for="description" class="form-label">内容描述</label>
                <textarea class="form-control" id="description" name="description" rows="3"><?php echo htmlspecialchars($content['description']); ?></textarea>
                <div class="form-text">简短描述该内容，将显示在页面上</div>
            </div>
            
            <!-- 特性设置 -->
            <h5 class="mb-3 mt-4">特性设置</h5>
            
            <div class="row mb-3">
                <div class="col-md-4">
                    <label for="color_code" class="form-label">颜色代码</label>
                    <input type="color" class="form-control form-control-color" id="color_code" name="color_code" value="<?php echo htmlspecialchars($content['color_code'] ?: '#FFFFFF'); ?>" title="选择颜色">
                    <div class="form-text">适用于颜色类内容，例如"红色"</div>
                </div>
                
                <div class="col-md-4">
                    <label for="content_order" class="form-label">显示顺序</label>
                    <input type="number" class="form-control" id="content_order" name="content_order" value="<?php echo $content['content_order']; ?>" min="0">
                    <div class="form-text">数字越小越靠前显示</div>
                </div>
                
                <div class="col-md-4">
                    <div class="form-check form-switch mt-4">
                        <input class="form-check-input" type="checkbox" id="is_active" name="is_active" <?php echo $content['is_active'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_active">是否显示</label>
                    </div>
                </div>
            </div>
            
            <!-- 音频设置 -->
            <h5 class="mb-3 mt-4">音频设置</h5>
            
            <div class="mb-3">
                <label for="title_audio" class="form-label">标题音频</label>
                <input type="file" class="form-control" id="title_audio" name="title_audio" accept="audio/*">
                <div class="form-text">上传与内容标题对应的音频文件，用户点击喇叭图标时播放</div>
            </div>
            
            <?php if ($titleAudio): ?>
                <div class="mb-3">
                    <div class="card">
                        <div class="card-body">
                            <h6 class="card-subtitle mb-2 text-muted">当前音频</h6>
                            <div class="d-flex align-items-center">
                                <audio controls src="<?php echo htmlspecialchars($titleAudio['file_path']); ?>" style="height: 30px;"></audio>
                                <span class="ms-3"><?php echo htmlspecialchars($titleAudio['file_name']); ?></span>
                                <input type="hidden" name="existing_audio_id" value="<?php echo $titleAudio['media_id']; ?>">
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- 保存后动作 -->
            <div class="mb-3 mt-4">
                <label class="form-label">保存后</label>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="after_save" id="after_save_list" value="list" checked>
                    <label class="form-check-label" for="after_save_list">
                        返回内容列表
                    </label>
                </div>
                <?php if (!$isEdit): ?>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="after_save" id="after_save_add_new" value="add_new">
                        <label class="form-check-label" for="after_save_add_new">
                            继续添加新内容
                        </label>
                    </div>
                <?php endif; ?>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="after_save" id="after_save_add_examples" value="add_examples">
                    <label class="form-check-label" for="after_save_add_examples">
                        添加内容示例
                    </label>
                </div>
            </div>
            
            <!-- 提交按钮 -->
            <div class="mt-4">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save"></i> 保存内容
                </button>
                <a href="cognitive_contents.php?module_id=<?php echo $moduleId; ?>" class="btn btn-outline-secondary ms-2">取消</a>
            </div>
        </form>
    </div>
</div>

<!-- 帮助提示 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-info-circle me-1"></i> 帮助提示
    </div>
    <div class="card-body">
        <p>内容创建步骤：</p>
        <ol>
            <li>填写内容基本信息（标题、描述等）</li>
            <li>上传对应的音频文件（如需要）</li>
            <li>保存后，添加内容示例（图片、音频等）</li>
        </ol>
        <p><strong>颜色代码</strong>：如果是颜色类内容（如"红色"），可以设置对应的颜色代码，用于显示颜色样本。</p>
    </div>
</div>

<script>
// 根据内容标题自动生成标识符
document.addEventListener('DOMContentLoaded', function() {
    const contentTitleInput = document.getElementById('content_title');
    const contentKeyInput = document.getElementById('content_key');
    
    // 只有在新增模式下才自动生成
    if (!<?php echo $isEdit ? 'true' : 'false'; ?>) {
        contentTitleInput.addEventListener('blur', function() {
            if (contentKeyInput.value === '') {
                let key = contentTitleInput.value
                    .toLowerCase()
                    .replace(/[\u4e00-\u9fa5]/g, '') // 移除中文字符
                    .replace(/[^\w\s-]/g, '') // 移除特殊字符
                    .replace(/\s+/g, '-') // 空格转为短横线
                    .replace(/-+/g, '-') // 合并多个短横线
                    .replace(/^-+|-+$/g, ''); // 移除首尾短横线
                
                // 如果结果为空（全是中文），则用拼音首字母或英文
                if (key === '') {
                    // 这里简化处理，实际可能需要更复杂的中文转拼音
                    const firstChar = contentTitleInput.value.charAt(0);
                    key = firstChar.charCodeAt(0).toString();
                }
                
                contentKeyInput.value = key;
            }
        });
    }
});
</script>

<?php require_once 'includes/footer.php'; ?> 